<?php

namespace app\common\model;

use think\Db;
use think\Exception;
use think\Model;

class AfterSales extends Model
{
	// 表名
	protected $name = 'after_sales';
	
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = true;
	
	
	// 追加属性
	protected $append = [
		'type_text',
		'status_text',
		'create_time_text',
		'update_time_text',
		'result_text'
	];
	
	//字典中设置的售后状态ID
	const DICTIONARY_GOODS_STATUS_ID = 2;
	//字典中设置的退款原因ID
	const DICTIONARY_RETURN_MONEY_REASON_ID = 5;
	//字典中设置的换货原因ID
	const DICTIONARY_EXCHANGE_REASON_ID = 5;
	
	
	const TYPE_ONLY_MONEY = 1;
	const TYPE_MONEY_PRODICT = 2;
	const TYPE_EXCHANGE = 3;
	
	public static $_type = [
		self::TYPE_ONLY_MONEY => '仅退款',
		self::TYPE_MONEY_PRODICT => '退货退款',
		self::TYPE_EXCHANGE => '换货'
	];
	
	/**
	 * @return array 售后类型
	 */
	public function getTypeList()
	{
		return self::$_type;
	}
	
	const STATUS_CANCEL = 0;
	const STATUS_WAIT_BUS = 1;
	const STATUS_FINISH = 2;
	const STATUS_BUS_DISAGREE = 3;
	const STATUS_PLATFORM_JOIN = 4;
	
	//售后状态
	public function getStatusList()
	{
		return [
			self::STATUS_CANCEL => '用户已取消',
			self::STATUS_WAIT_BUS => '等待卖家处理',
			self::STATUS_FINISH => '售后结束',
			self::STATUS_BUS_DISAGREE => '卖家拒绝申请',
			self::STATUS_PLATFORM_JOIN => '客服介入中',
		];
	}
	
	const RESULT_USER = 1;
	const RESULT_BUS = 2;
	//处理结果
	public function getResultList()
	{
		return [
			self::RESULT_USER => '申请成功',
			self::RESULT_BUS => '申请失败'
		];
	}
	
	public function getTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['type'];
		$list = $this->getTypeList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getStatusTextAttr($value, $data)
	{
		$value = $value ? $value : $data['status'];
		$list = $this->getStatusList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getCreateTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['create_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getUpdateTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['update_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getResultTextAttr($value, $data)
	{
		$value = $value ? $value : $data['result'];
		$list = $this->getResultList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	protected function setCreateTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	protected function setUpdateTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	public function user() {
		return $this->belongsTo('User', 'user_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function order() {
		return $this->belongsTo('Order', 'order_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	public function ordergoods() {
		return $this->belongsTo('OrderGoods', 'order_item_id', 'id', '', 'left')->setEagerlyType(0);
	}
	
	
	/**
	 * 同意售后
	 * @param $id
	 * @param $role
	 * @param string $remark
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function pass($id, $role, $remark='') {
		$this->startTrans();
		$row = $this->find($id);
		try {
			//更改售后状态
			$res = $this
				->where(['id' => $id])
				->update([
					'status' => self::STATUS_FINISH,
					'update_time' => time(),
					'result' => self::RESULT_USER
				]);
			if(!$res) {
				throw new Exception('更改售后记录状态出错');
			}
			
			//记录详情
			$itemModel = new AfterItem();
			if($role == $itemModel::ROLE_BUS) {
				$itemRes = $itemModel->addItem($id, $itemModel::ROLE_BUS, '卖家同意售后','卖家同意售后，售后完成');
			} else {
				$itemRes = $itemModel->addItem($id, $itemModel::ROLE_SYS, '系统处理完成','系统处理完成:'.$remark);
			}
			if(!$itemRes) {
				throw new Exception('添加售后记录出错');
			}
			
			//判断售后类型,给用户退钱
			if($row['type'] == self::TYPE_MONEY_PRODICT || $row['type'] == self::TYPE_ONLY_MONEY) {
				$user = Db::name('user')->find($row['user_id']);
				$userRes = Db::name('user')->where(['id' => $row['user_id']])->setInc('balance', $row['amount']);
				if(!$userRes) {
					throw new Exception('退款出错');
				}
				
				//添加资金记录
				$logModel = new FundsRecord();
				$logRes = $logModel->addRecord($row['user_id'], $row['amount'], $user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_AFTERSALES_RETURN, $row['order_id'], '售后退款');
				if(!$logRes) {
					throw new Exception('记录退款记录出错');
				}
			}
			
			$orderGoodsModel = new OrderGoods();
			//类型为退货退款的，更改订单商品状态
			if($row['type'] == self::TYPE_MONEY_PRODICT || $row['type'] == self::TYPE_EXCHANGE) {
				if($row['type'] == self::TYPE_MONEY_PRODICT) {
					$data['is_send'] = $orderGoodsModel::SEND_RETURN;
				} else {
					$data['is_send'] = $orderGoodsModel::SEND_EXCHANGE;
				}
				$goodsRes = Db::name('orderGoods')->where(['id' => $row['order_item_id']])->update($data);
				if(!$goodsRes) {
					throw new Exception('更改商品状态出错');
				}
			}
			
			$orderModel = new Order();
			$order = Db::name('order')->where(['id' => $row['order_id']])->find();
			//如果类型为退货退款或者类型为退款且还没发货，关闭订单
			if($row['type'] == self::TYPE_MONEY_PRODICT || ($row['type'] == self::TYPE_ONLY_MONEY && $order['order_status'] == $orderModel::STATUS_WAIT_DELIVERY)) {
				//查找是否还存在没有退货的商品，没有的话就关闭订单
				$goodsCount = $orderGoodsModel->where(['order_id' => $row['order_id'], 'is_send' => ['neq', $orderGoodsModel::SEND_RETURN]])->count();
				if(!$goodsCount) {
					$orderRes = $orderModel->where(['id' => $row['order_id']])->update([
						'order_status' => $orderModel::STATUS_CLOSE,
						'close_type' => $orderModel::CLOSE_TYPE_AFTERSALES,
						'update_time' => time(),
					]);
				
					if(!$orderRes) {
						throw new Exception('关闭订单出错');
					}
				}
			}
			
			$this->commit();
			return true;
			
		} catch (Exception $e) {
			$this->rollback();
			$this->error = $e->getMessage();
			return false;
		}
	}
}
